"""
AI集成 - Django Admin 配置
管理AI相关的后台界面
"""
from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Avg
from django.urls import reverse
from django.utils.safestring import mark_safe

from .models import (
    AIServiceConfig, AIRequestLog, AIQuestionGeneration,
    AIAutoGrading, AIAnalysis, AIRecommendation
)


@admin.register(AIServiceConfig)
class AIServiceConfigAdmin(admin.ModelAdmin):
    """AI服务配置管理"""
    list_display = [
        'name', 'service_type', 'model_name', 'is_active',
        'is_primary', 'daily_usage', 'last_used', 'created_at'
    ]
    list_filter = [
        'service_type', 'is_active', 'is_primary', 'created_at'
    ]
    search_fields = ['name', 'service_type', 'model_name']
    readonly_fields = [
        'id', 'daily_usage', 'last_used', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'service_type', 'model_name', 'is_primary')
        }),
        ('API配置', {
            'fields': ('api_key', 'api_url', 'config_params')
        }),
        ('使用限制', {
            'fields': ('rate_limit', 'daily_limit', 'is_active')
        }),
        ('使用统计', {
            'fields': ('daily_usage', 'last_used'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def get_queryset(self, request):
        return super().get_queryset(request).order_by('-is_primary', '-is_active')

    def save_model(self, request, obj, form, change):
        # 确保只有一个主要配置
        if obj.is_primary:
            AIServiceConfig.objects.filter(
                service_type=obj.service_type,
                is_primary=True
            ).exclude(id=obj.id if change else None).update(is_primary=False)
        super().save_model(request, obj, form, change)


class AIRequestLogInline(admin.TabularInline):
    """AI请求日志内联"""
    model = AIRequestLog
    extra = 0
    readonly_fields = [
        'request_type', 'status', 'response_time', 'token_count', 'cost', 'created_at'
    ]
    fields = [
        'request_type', 'status', 'response_time', 'token_count', 'cost', 'created_at'
    ]

    def has_add_permission(self, request, obj):
        return False


@admin.register(AIRequestLog)
class AIRequestLogAdmin(admin.ModelAdmin):
    """AI请求日志管理"""
    list_display = [
        'request_type', 'user_info', 'service_config_name',
        'status', 'response_time', 'cost', 'created_at'
    ]
    list_filter = [
        'request_type', 'status', 'service_config', 'created_at'
    ]
    search_fields = ['user__real_name', 'user__username']
    readonly_fields = [
        'id', 'request_type', 'service_config', 'user', 'input_data',
        'output_data', 'status', 'error_message', 'response_time',
        'token_count', 'cost', 'created_at'
    ]
    date_hierarchy = 'created_at'

    def user_info(self, obj):
        """用户信息"""
        if obj.user:
            return f"{obj.user.real_name} ({obj.user.username})"
        return "系统"
    user_info.short_description = '用户'

    def service_config_name(self, obj):
        """服务配置名称"""
        return obj.service_config.name if obj.service_config else "-"
    service_config_name.short_description = 'AI服务'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('user', 'service_config')


@admin.register(AIQuestionGeneration)
class AIQuestionGenerationAdmin(admin.ModelAdmin):
    """AI题目生成管理"""
    list_display = [
        'user_info', 'generation_type', 'question_type',
        'count', 'generated_count', 'accepted_count',
        'quality_score', 'review_status', 'created_at'
    ]
    list_filter = [
        'generation_type', 'question_type', 'difficulty', 'review_status', 'created_at'
    ]
    search_fields = ['user__real_name', 'user__username']
    readonly_fields = [
        'id', 'user', 'generated_questions', 'accepted_questions',
        'quality_score', 'ai_request_log', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'generation_type', 'question_type', 'difficulty')
        }),
        ('生成参数', {
            'fields': ('knowledge_points', 'count')
        }),
        ('生成结果', {
            'fields': ('generated_questions', 'accepted_questions', 'quality_score')
        }),
        ('审核状态', {
            'fields': ('review_status', 'ai_request_log')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def user_info(self, obj):
        """用户信息"""
        return f"{obj.user.real_name} ({obj.user.username})"
    user_info.short_description = '用户'

    def generated_count(self, obj):
        """生成题目数"""
        return len(obj.generated_questions) if obj.generated_questions else 0
    generated_count.short_description = '生成数量'

    def accepted_count(self, obj):
        """采纳题目数"""
        return len(obj.accepted_questions) if obj.accepted_questions else 0
    accepted_count.short_description = '采纳数量'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('user', 'ai_request_log')


@admin.register(AIAutoGrading)
class AIAutoGradingAdmin(admin.ModelAdmin):
    """AI自动评分管理"""
    list_display = [
        'answer_info', 'grading_type', 'ai_score',
        'confidence', 'final_score', 'is_approved', 'human_reviewer', 'created_at'
    ]
    list_filter = [
        'grading_type', 'is_approved', 'created_at'
    ]
    search_fields = [
        'examination_answer__student__real_name',
        'examination_answer__exam_session__examination__title'
    ]
    readonly_fields = [
        'id', 'examination_answer', 'ai_score', 'confidence',
        'ai_request_log', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('评分信息', {
            'fields': ('examination_answer', 'grading_type', 'max_score')
        }),
        ('AI评分结果', {
            'fields': ('ai_score', 'confidence', 'scoring_details', 'feedback')
        }),
        ('人工审核', {
            'fields': ('human_reviewer', 'final_score', 'is_approved')
        }),
        ('相关信息', {
            'fields': ('ai_request_log', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def answer_info(self, obj):
        """答案信息"""
        answer = obj.examination_answer
        return f"{answer.exam_session.user.real_name} - {answer.exam_question.question.title[:30]}..."
    answer_info.short_description = '答案'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'examination_answer__exam_session__user',
            'examination_answer__exam_question__question',
            'human_reviewer',
            'ai_request_log'
        )


@admin.register(AIAnalysis)
class AIAnalysisAdmin(admin.ModelAdmin):
    """AI分析管理"""
    list_display = [
        'analysis_type', 'target_info', 'status',
        'confidence_level', 'created_at', 'updated_at'
    ]
    list_filter = [
        'analysis_type', 'status', 'created_at'
    ]
    search_fields = []
    readonly_fields = [
        'id', 'analysis_type', 'target_object_type', 'target_object_id',
        'analysis_results', 'insights', 'recommendations',
        'confidence_level', 'completeness', 'status',
        'ai_request_log', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('analysis_type', 'target_object_type', 'target_object_id')
        }),
        ('分析结果', {
            'fields': ('analysis_results', 'insights', 'recommendations'),
            'classes': ('collapse',)
        }),
        ('质量指标', {
            'fields': ('confidence_level', 'completeness', 'status')
        }),
        ('相关信息', {
            'fields': ('ai_request_log', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def target_info(self, obj):
        """目标信息"""
        return f"{obj.target_object_type}:{obj.target_object_id}"
    target_info.short_description = '分析目标'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('ai_request_log')


@admin.register(AIRecommendation)
class AIRecommendationAdmin(admin.ModelAdmin):
    """AI推荐管理"""
    list_display = [
        'user_info', 'recommendation_type', 'recommendations_count',
        'relevance_score', 'is_helpful', 'valid_until', 'created_at'
    ]
    list_filter = [
        'recommendation_type', 'is_helpful', 'is_active', 'created_at'
    ]
    search_fields = ['user__real_name', 'user__username']
    readonly_fields = [
        'id', 'user', 'recommendations', 'reasoning',
        'relevance_score', 'diversity_score', 'user_feedback',
        'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'recommendation_type', 'valid_until', 'is_active')
        }),
        ('推荐内容', {
            'fields': ('recommendations', 'reasoning')
        }),
        ('推荐质量', {
            'fields': ('relevance_score', 'diversity_score')
        }),
        ('用户反馈', {
            'fields': ('user_feedback', 'is_helpful'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def user_info(self, obj):
        """用户信息"""
        return f"{obj.user.real_name} ({obj.user.username})"
    user_info.short_description = '用户'

    def recommendations_count(self, obj):
        """推荐数量"""
        return len(obj.recommendations) if obj.recommendations else 0
    recommendations_count.short_description = '推荐数量'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('user')


# 自定义Admin站点标题
admin.site.site_header = 'AI-SOES AI管理后台'
admin.site.site_title = 'AI-SOES AI服务'
admin.site.index_title = '智能在线考试系统 - AI集成模块'